package com.ruoyi.common.utils;


import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.ruoyi.common.config.BaseConfig;

import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;

public class QRCodeUtil {
    public static String generateQRCodeImage(String text){
        try{
            String filePath= BaseConfig.Config.filePath+"/qrcode";

            int width = 300;
            int height = 300;
            String fileType = "png";
            filePath=filePath+"/"+text+"."+fileType;
            QRCodeWriter qrCodeWriter = new QRCodeWriter();
            Map<EncodeHintType, Object> hintMap = new HashMap<>();
            hintMap.put(EncodeHintType.CHARACTER_SET, "UTF-8");
            hintMap.put(EncodeHintType.MARGIN, 1);
            BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height, hintMap);

            Path path = FileSystems.getDefault().getPath(filePath);
            MatrixToImageWriter.writeToPath(bitMatrix, fileType, path);
            String qrCodeImageUrl = path.toString().substring(1).replaceAll("/root","");
            if(qrCodeImageUrl.contains("root")){
                qrCodeImageUrl=qrCodeImageUrl.replaceAll("/root","").replaceAll("root","");
            }
            System.err.println("QRCodeUtil=========="+qrCodeImageUrl);
            return qrCodeImageUrl;
        }catch (Exception e){
            e.printStackTrace();
            return "";
        }
    }
}
